import { message } from 'ant-design-vue';
import { collectionLine, cancelCollectionLine, getPipelineData } from '@/api/pipeline';

export const usePipeline = () => {
  const pipelineCode = ref<string>('');
  const pipelineData = ref<Pipeline.BaseInfo>({} as Pipeline.BaseInfo);
  const isFavorite = ref<boolean>(false);

  // 获得当前流水线的基础信息
  const fetchPipelineInfo = async () => {
    const data = await getPipelineData(pipelineCode.value);
    isFavorite.value = data.isFavorite;
    pipelineData.value = data;
  };

  const starColor = computed(() => {
    return isFavorite.value ? '#ffbf00' : '#849cb6';
  });

  const starPipeline = async () => {
    if (!isFavorite.value) {
      await collectionLine(pipelineCode.value)
        .then(() => {
          message.destroy();
          message.success('收藏成功');
          isFavorite.value = true;
        })
        .catch(() => {
          message.destroy();
          message.error('收藏失败');
          isFavorite.value = false;
        });
    } else {
      await cancelCollectionLine(pipelineCode.value)
        .then(() => {
          message.destroy();
          message.success('已取消收藏');
          isFavorite.value = false;
        })
        .catch(() => {
          message.destroy();
          message.error('取消收藏失败');
          isFavorite.value = true;
        });
    }
  };

  return {
    pipelineData,
    pipelineCode,
    starColor,
    starPipeline,
    fetchPipelineInfo,
  };
};
